#!/opt/bin/python
#!/usr/bin/env python
import serial
import struct
import time
import pymysql
from datetime import datetime

# 数据库连接配置
db_config = {
    'host': '*.*.*.*',  # 数据库服务器地址
    'user': '***',  # 数据库用户名
    'password': '***',  # 数据库密码
    'database': '***',  # 数据库名称
    'port' : ****,
    'charset': 'utf8mb4',  # 字符集
    'cursorclass': pymysql.cursors.DictCursor,  # 返回字典类型的游标
}

def parse_sensor_data(frame):
    """解析传感器数据帧"""
    if len(frame) != 7:
        return None

    header = frame[0:2]
    target_type = frame[2]
    distance_bytes = frame[3:5]
    footer = frame[5:7]

    if header != b'\xaa\xaa' or footer != b'\x55\x55':
        return None

    distance = struct.unpack('<H', distance_bytes)[0]
    return target_type, distance

def read_and_decode_sensor_data(port, baudrate=256000):
    """读取并解码传感器数据，并上传到数据库"""
    ser = serial.Serial(port, baudrate, timeout=None)  # 设置timeout为None以非阻塞方式读取
    buffer = bytearray()
    connection = None

    try:
        # 连接到数据库
        connection = pymysql.connect(**db_config)

        while True:
            # 读取串口中的可用数据
            chunk = ser.read(ser.in_waiting)
            if chunk:
                buffer.extend(chunk)

                # 尝试从缓冲区中解析出完整的数据帧
                while len(buffer) >= 7:
                    frame = buffer[:7]
                    result = parse_sensor_data(frame)

                    if result:
                        target_type, distance = result
                        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间

                        # 根据目标类型生成数据库插入语句
                        event_description = None
                        if target_type == 0x01:
                            event_description = '有人运动'
                        elif target_type == 0x02:
                            event_description = '物体微动'

                        # 插入数据到数据库
                        if event_description:
                            with connection.cursor() as cursor:
                                sql = "INSERT INTO motion_events (event_time, event_description) VALUES (%s, %s)"
                                cursor.execute(sql, (timestamp, event_description))
                            connection.commit()

                        # 删除已解析的数据帧
                        del buffer[:7]
                    else:
                        # 如果无法解析，则丢弃第一个字节并继续尝试
                        del buffer[0]
#        time.sleep(0.5)
    except KeyboardInterrupt:
        print("\n用户中断，关闭串口连接和数据库连接。")
    except pymysql.Error as e:
        print(f"数据库错误: {e}")
    finally:
        # 关闭串口和数据库连接
        if connection:
            connection.close()
        ser.close()

if __name__ == "__main__":
    # 修改为实际的串口号，例如COM3（Windows）或/dev/ttyUSB0（Linux）
    read_and_decode_sensor_data("/dev/ttyUSB0", baudrate=256000)
